package com.niuwa.p2p.service.impl.yeepay;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.xml.bind.JAXB;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.niuwa.p2p.core.constant.YeePayBizTypeEnum;
import com.niuwa.p2p.core.constant.YeePayBussinesEnum;
import com.niuwa.p2p.core.constant.YeePayClassTypeEnum;
import com.niuwa.p2p.core.constant.YeePayModeEnum;
import com.niuwa.p2p.core.constant.YeePayServiceEnum;
import com.niuwa.p2p.core.constant.YeePaySubjoinEnum;
import com.niuwa.p2p.core.utils.MobileUtil;
import com.niuwa.p2p.core.utils.UUIDUtil;
import com.niuwa.p2p.core.utils.yeepay.JaxbUtil;
import com.niuwa.p2p.core.utils.yeepay.SignUtil;
import com.niuwa.p2p.core.utils.yeepay.WebUtil;
import com.niuwa.p2p.core.utils.yeepay.JaxbUtil.CollectionWrapper;
import com.niuwa.p2p.entity.yeepay.TenderExtend;
import com.niuwa.p2p.entity.yeepay.TenderProperty;
import com.niuwa.p2p.entity.yeepay.YeePayAutoTransferRequest;
import com.niuwa.p2p.entity.yeepay.YeePayBaseResponse;
import com.niuwa.p2p.entity.yeepay.YeePayBindRequest;
import com.niuwa.p2p.entity.yeepay.YeePayEnterpriseRegisterRequest;
import com.niuwa.p2p.entity.yeepay.YeePayLogInfo;
import com.niuwa.p2p.entity.yeepay.YeePayMessage;
import com.niuwa.p2p.entity.yeepay.YeePayMongoInfo;
import com.niuwa.p2p.entity.yeepay.YeePayRechargeRequest;
import com.niuwa.p2p.entity.yeepay.YeePayRegisterRequest;
import com.niuwa.p2p.entity.yeepay.YeePayUnBindRequest;
import com.niuwa.p2p.entity.yeepay.YeePayWithdrawRequest;
import com.niuwa.p2p.entity.yeepay.YeePayeAutoRepaymentRequest;
import com.niuwa.p2p.entity.yeepay.YeepayCpTenderRequest;
import com.niuwa.p2p.entity.yeepay.YeepayCpTransferRequest;
import com.niuwa.p2p.entity.yeepay.cp.CpExtendRequest;
import com.niuwa.p2p.entity.yeepay.supple.AutoTransactionRequest;
import com.niuwa.p2p.entity.yeepay.supple.CancelAuthorizeAutoRequest;
import com.niuwa.p2p.entity.yeepay.supple.CancelAutoRepaymentRequest;
import com.niuwa.p2p.entity.yeepay.supple.CompleteTransactionRequest;
import com.niuwa.p2p.entity.yeepay.supple.CpTransactionResponse;
import com.niuwa.p2p.entity.yeepay.supple.DirectTransactionResponse;
import com.niuwa.p2p.entity.yeepay.supple.FreezereRecordResponse;
import com.niuwa.p2p.entity.yeepay.supple.RechargeRecordResponse;
import com.niuwa.p2p.entity.yeepay.supple.SuppleAccountRequest;
import com.niuwa.p2p.entity.yeepay.supple.SuppleAccountResponse;
import com.niuwa.p2p.entity.yeepay.supple.SuppleFreezeRequest;
import com.niuwa.p2p.entity.yeepay.supple.SuppleFreezeResponse;
import com.niuwa.p2p.entity.yeepay.supple.SuppleSingleQueryRequest;
import com.niuwa.p2p.entity.yeepay.supple.SuppleSingleQueryResponse;
import com.niuwa.p2p.entity.yeepay.supple.SuppleUnFreezeRequest;
import com.niuwa.p2p.entity.yeepay.supple.SuppleUnFreezeResponse;
import com.niuwa.p2p.entity.yeepay.supple.WithdrawRecordResponse;
import com.niuwa.p2p.entity.yeepay.supple.YeePayDirectTransactionRequest;
import com.niuwa.p2p.service.yeepay.YeePayLogService;
import com.niuwa.p2p.service.yeepay.YeePayMongoService;
import com.niuwa.p2p.service.yeepay.YeePayService;

/**
 * 
 * @title 易宝支付调用服务
 *
 * @author tennyqin
 * @version 1.0
 * @created 2015年4月7日
 */
@Service
public class YeePayServiceImpl implements YeePayService {

	@Value("#{propertiesReader['yeepay.pfx.path']}")
	private String pfx;

	@Value("#{propertiesReader['yeepay.pfx.host']}")
	private String host;

	@Value("#{propertiesReader['yeepay.user.platformNo']}")
	private String platformNo;

	@Value("#{propertiesReader['yeepay.service.notifyUrl']}")
	private String notifyUrl;

	@Value("#{propertiesReader['yeepay.service.directUrl']}")
	private String directUrl;

	@Value("#{propertiesReader['yeepay.p2p.callBackUrl']}")
	private String callbackUrl;

	@Autowired
	private YeePayLogService yeePayLogService;

//	@Autowired
	private YeePayMongoService yeePayMongoService;

	private static Logger logger = Logger.getLogger(YeePayServiceImpl.class); // 日志记录

	@Override
	public YeePayBaseResponse doRegister(YeePayRegisterRequest request) {
		request.setRequestNo("nwPre_"
				+ String.valueOf(UUIDUtil.getBigIntegerUUid()));
		request.setPlatformNo(platformNo);
		request.setNotifyUrl(notifyUrl);
		request.setCallbackUrl(callbackUrl);
		return doSignNet(request, host + "/toRegister", null,
				request.getRequestNo(), request.getPlatformUserNo());
	}

	@Override
	public YeePayBaseResponse doRecharge(YeePayRechargeRequest request) {
		request.setRequestNo("nwRc_"
				+ String.valueOf(UUIDUtil.getBigIntegerUUid()));
		request.setPlatformNo(platformNo);
		request.setNotifyUrl(notifyUrl);
		request.setCallbackUrl(callbackUrl);
		return doSignNet(request, host + "/toRecharge", null,
				request.getRequestNo(), request.getPlatformUserNo());
	}

	@Override
	public YeePayBaseResponse DoWithdraw(YeePayWithdrawRequest request) {
		request.setRequestNo("nwWd_"
				+ String.valueOf(UUIDUtil.getBigIntegerUUid()));
		request.setPlatformNo(platformNo);
		request.setNotifyUrl(notifyUrl);
		request.setCallbackUrl(callbackUrl);
		return doSignNet(request, host + "/toWithdraw", null,
				request.getRequestNo(), request.getPlatformUserNo());
	}

	@Override
	public YeePayBaseResponse DoBindBankCard(YeePayBindRequest request) {
		request.setRequestNo("nwBD_"
				+ String.valueOf(UUIDUtil.getBigIntegerUUid()));
		request.setPlatformNo(platformNo);
		request.setNotifyUrl(notifyUrl);
		request.setCallbackUrl(callbackUrl);
		return doSignNet(request, host + "/toBindBankCard", null,
				request.getRequestNo(), request.getPlatformUserNo());
	}

	@Override
	public YeePayBaseResponse UnbindBankCard(YeePayUnBindRequest request) {
		request.setRequestNo("nwUnBD_"
				+ String.valueOf(UUIDUtil.getBigIntegerUUid()));
		request.setPlatformNo(platformNo);
		request.setCallbackUrl(callbackUrl);
		return doSignNet(request, host + "/toUnbindBankCard", null,
				request.getRequestNo(), request.getPlatformUserNo());
	}

	@Override
	public YeePayBaseResponse doEnterpriseRegister(
			YeePayEnterpriseRegisterRequest request) {
		request.setRequestNo("nwEre_"
				+ String.valueOf(UUIDUtil.getBigIntegerUUid()));
		request.setPlatformNo(platformNo);
		request.setNotifyUrl(notifyUrl);
		request.setCallbackUrl(callbackUrl);
		return doSignNet(request, host + "/toEnterpriseRegister", null,
				request.getRequestNo(), request.getPlatformUserNo());
	}

	// 转账
	@Override
	public YeePayBaseResponse doTransfer(YeepayCpTransferRequest request) {
		request.setRequestNo("nwTf_"
				+ String.valueOf(UUIDUtil.getBigIntegerUUid()));
		request.setPlatformNo(platformNo);
		request.setNotifyUrl(notifyUrl);
		request.setUserType("MEMBER");
		request.setCallbackUrl(callbackUrl);
		return doSignNet(request, host + "/toCpTransaction", null,
				request.getRequestNo(), request.getPlatformUserNo());
	}

	// 投标 、还款、债权转让 [注意类型不一样参数对应不一样]
	@Override
	public YeePayBaseResponse doCpTransaction(YeepayCpTenderRequest request,
			CpExtendRequest cPrequest) {
		request.setPlatformNo(platformNo);
		request.setNotifyUrl(notifyUrl);
		request.setUserType("MEMBER");
		request.setCallbackUrl(callbackUrl);
		List<TenderProperty> properts = new ArrayList<TenderProperty>();
		TenderExtend tenderExtend = new TenderExtend();
		if (request.getBizType() == YeePayBizTypeEnum.TENDER) { // 投标
			request.setRequestNo("nwTd_"
					+ String.valueOf(UUIDUtil.getBigIntegerUUid()));
			TenderProperty propertNo = new TenderProperty();
			propertNo.setName("tenderOrderNo");
			propertNo.setValue(cPrequest.getTenderEntity().getTenderOrderNo());
			properts.add(propertNo);

			TenderProperty propertName = new TenderProperty();
			propertName.setName("tenderName");
			propertName.setValue(cPrequest.getTenderEntity().getTenderName());
			properts.add(propertName);

			TenderProperty propertAmount = new TenderProperty();
			propertAmount.setName("tenderAmount");
			propertAmount.setValue(cPrequest.getTenderEntity()
					.getTenderAmount());
			properts.add(propertAmount);

			TenderProperty propertDescription = new TenderProperty();
			propertDescription.setName("tenderDescription");
			propertDescription.setValue(cPrequest.getTenderEntity()
					.getTenderDescription());
			properts.add(propertDescription);

			TenderProperty propertPlat = new TenderProperty();
			propertPlat.setName("borrowerPlatformUserNo");
			propertPlat.setValue(cPrequest.getTenderEntity()
					.getBorrowerPlatformUserNo());
			properts.add(propertPlat);

			tenderExtend.setProperty(properts);
			request.setExtend(tenderExtend);
		}
		if (request.getBizType() == YeePayBizTypeEnum.REPAYMENT) { // 还款
			request.setRequestNo("nwRep_"
					+ String.valueOf(UUIDUtil.getBigIntegerUUid()));
			TenderProperty propertNo = new TenderProperty();
			propertNo.setName("tenderOrderNo ");
			propertNo.setValue(cPrequest.getRepaymentEntity()
					.getTenderOrderNo());
			properts.add(propertNo);
			tenderExtend.setProperty(properts);
			request.setExtend(tenderExtend);
		}
		if (request.getBizType() == YeePayBizTypeEnum.CREDIT_ASSIGNMENT) { // 债权转让
			request.setRequestNo("nwCred_"
					+ String.valueOf(UUIDUtil.getBigIntegerUUid()));
			TenderProperty propertNo = new TenderProperty();
			propertNo.setName("tenderOrderNo ");
			propertNo.setValue(cPrequest.getCreditAssignment()
					.getTenderOrderNo());
			properts.add(propertNo);

			TenderProperty propertPlat = new TenderProperty();
			propertPlat.setName("creditorPlatformUserNo ");
			propertPlat.setValue(cPrequest.getCreditAssignment()
					.getCreditorPlatformUserNo());
			properts.add(propertPlat);

			TenderProperty propertReq = new TenderProperty();
			propertReq.setName("originalRequestNo ");
			propertReq.setValue(cPrequest.getCreditAssignment()
					.getOriginalRequestNo());
			properts.add(propertReq);

			tenderExtend.setProperty(properts);
			request.setExtend(tenderExtend);
		}
		return doSignNet(request, host + "/toCpTransaction", null,
				request.getRequestNo(), request.getPlatformUserNo(), cPrequest);
	}

	@Override
	public YeePayBaseResponse doAuthorizeAutoTransfer( // 投标
			YeePayAutoTransferRequest request) {
		request.setRequestNo("nwAtf_"
				+ String.valueOf(UUIDUtil.getBigIntegerUUid()));
		request.setPlatformNo(platformNo);
		request.setNotifyUrl(notifyUrl);
		request.setCallbackUrl(callbackUrl);
		return doSignNet(request, host + "/toAuthorizeAutoTransfer", null,
				request.getRequestNo(), request.getPlatformUserNo());
	}

	@Override
	public YeePayBaseResponse doAuthorizeAutoRepayment( // 转账
			YeePayeAutoRepaymentRequest request) {
		request.setRequestNo("nwARep_"
				+ String.valueOf(UUIDUtil.getBigIntegerUUid()));
		request.setPlatformNo(platformNo);
		request.setNotifyUrl(notifyUrl);
		request.setCallbackUrl(callbackUrl);
		return doSignNet(request, host + "/toAuthorizeAutoRepayment", null,
				request.getRequestNo(), request.getPlatformUserNo());
	}

	@Override
	public SuppleAccountResponse doAccoutInfo(SuppleAccountRequest request) {
		request.setPlatformNo(platformNo);
		return doSignDirectAccount(request, directUrl,
				YeePaySubjoinEnum.ACCOUNT_INFO.toString(),
				request.getPlatformUserNo());
	}

	@Override
	public SuppleFreezeResponse doFreeze(SuppleFreezeRequest request) {
		request.setPlatformNo(platformNo);
		request.setRequestNo("nwFre_"
				+ String.valueOf(UUIDUtil.getBigIntegerUUid()));
		return doSignDirectFreeze(request, directUrl, "FREEZE",
				request.getRequestNo(), request.getPlatformUserNo());
	}

	@Override
	public SuppleUnFreezeResponse doUnFreeze(SuppleUnFreezeRequest request) {
		request.setPlatformNo(platformNo);
		return doSignDirectUnFreeze(request, directUrl, "UNFREEZE");
	}

	@Override
	public SuppleSingleQueryResponse doSingleQuery(
			SuppleSingleQueryRequest request) {
		request.setPlatformNo(platformNo);
		return doSignSingleQuery(request, directUrl, "QUERY",
				request.getRequestNo(), request.getMode());
	}

	@Override
	public DirectTransactionResponse doDirectTransaction(
			YeePayDirectTransactionRequest request) {
		request.setPlatformNo(platformNo);
		request.setUserType("MERCHANT");
		request.setBizType("TRANSFER");
		request.getDetail().setBizType("TRANSFER");
		request.setNotifyUrl(notifyUrl);
		request.setRequestNo("nwDTs_"
				+ String.valueOf(UUIDUtil.getBigIntegerUUid()));
		return doDirectTransaction(request, directUrl, "DIRECT_TRANSACTION",
				request.getRequestNo(), request.getPlatformUserNo());
	}

	@Override
	public DirectTransactionResponse doAutoTransaction(
			AutoTransactionRequest request) {
		request.setRequestNo("nwAts_"
				+ String.valueOf(UUIDUtil.getBigIntegerUUid()));
		request.setPlatformNo(platformNo);
		request.setNotifyUrl(notifyUrl);
		return doDirectTransaction(request, directUrl, "AUTO_TRANSACTION",
				request.getRequestNo(), request.getPlatformUserNo());
	}

	@Override
	public DirectTransactionResponse doCompleteTransaction(
			CompleteTransactionRequest request) {
		request.setPlatformNo(platformNo);
		request.setNotifyUrl(notifyUrl);
		return doDirectTransaction(request, directUrl, "COMPLETE_TRANSACTION",
				request.getRequestNo(),
				String.valueOf("nwCts_" + UUIDUtil.getBigIntegerUUid()));
	}

	@Override
	public DirectTransactionResponse doCancelAuthorizeAuto(
			CancelAuthorizeAutoRequest request) {
		request.setPlatformNo(platformNo);
		request.setRequestNo("nwCaa_"
				+ String.valueOf(UUIDUtil.getBigIntegerUUid()));
		return doDirectTransaction(request, directUrl,
				"CANCEL_AUTHORIZE_AUTO_TRANSFER", request.getRequestNo(),
				request.getPlatformUserNo());
	}

	@Override
	public DirectTransactionResponse doCancelAutoRepayment(
			CancelAutoRepaymentRequest request) {
		request.setPlatformNo(platformNo);
		request.setRequestNo("nwCarep_"
				+ String.valueOf(UUIDUtil.getBigIntegerUUid()));
		return doDirectTransaction(request, directUrl,
				"CANCEL_AUTHORIZE_AUTO_REPAYMENT", request.getRequestNo(),
				request.getPlatformUserNo());
	}

	// 网关连接
	private YeePayBaseResponse doSignNet(Object obj, String url,
			String service, String requestNo, String platformUserNo) {
		YeePayBaseResponse response = new YeePayBaseResponse();
		try {
			StringWriter w = new StringWriter();
			JAXB.marshal(obj, w);
			String s = w.toString();
			s = s.replaceAll("[\\r\\n]", "");
			StringBuffer params = new StringBuffer();
			params.append("req=" + s);
			params.append("&service=" + service);
			params.append("&sign=" + "r7B");
			response.setUrl(url);
			response.setMessage(params.toString());
			YeePayMessage yeePayMessage = writeLogger(response, obj);
			yeePayMessage.setRquestNo(requestNo);
			yeePayMessage.setPlatformUserNo(platformUserNo);
			insertDBLogger(yeePayMessage);
			// inserMongoDBKey(yeePayMessage, SignUtil.sign(s, pfx, "123qwe"));
			inserMongoDBKey(yeePayMessage, "r7B");
		} catch (Exception ex) {
			logger.error("执行签名操作失败!!", ex);
		}
		return response;
	}

	// 网关连接 [投标，还款，债权转让]
	private YeePayBaseResponse doSignNet(Object obj, String url,
			String service, String requestNo, String platformUserNo,
			CpExtendRequest cPrequest) {
		YeePayBaseResponse response = new YeePayBaseResponse();
		try {
			StringWriter w = new StringWriter();
			JAXB.marshal(obj, w);
			String s = w.toString();
			s = s.replaceAll("[\\r\\n]", "");
			StringBuffer params = new StringBuffer();
			params.append("req=" + s);
			params.append("&service=" + service);
			params.append("&sign=" + "r7B");
			response.setUrl(url);
			response.setMessage(params.toString());
			YeePayMessage yeePayMessage = writeLogger(response, cPrequest);
			yeePayMessage.setRquestNo(requestNo);
			yeePayMessage.setPlatformUserNo(platformUserNo);
			insertDBLogger(yeePayMessage);
			//inserMongoDBKey(yeePayMessage, SignUtil.sign(s, pfx, "123qwe"));
			inserMongoDBKey(yeePayMessage, "r7B");
		} catch (Exception ex) {
			logger.error("执行签名操作失败!!", ex);
		}
		return response;
	}

	// 直接连接冻结
	private SuppleFreezeResponse doSignDirectFreeze(Object obj, String url,
			String service, String requestNo, String platformUserNo) {
		SuppleFreezeResponse response = null;
		try {
			StringWriter w = new StringWriter();
			JAXB.marshal(obj, w);
			String s = w.toString();
			s = s.replaceAll("[\\r\\n]", "");
			StringBuffer params = new StringBuffer();
			params.append("req=" + s);
			params.append("&service=" + service);
			params.append("&sign=" + "r7B");
			String returnValue = WebUtil.sendPost(directUrl, params.toString());
			if (!MobileUtil.isEmpty(returnValue)) {
				JaxbUtil resultBinder = new JaxbUtil(
						SuppleFreezeResponse.class, CollectionWrapper.class);
				response = resultBinder.fromXml(returnValue);
			}
			response.setMessage(params.toString());
			YeePayMessage yeePayMessage = writeLogger(response, obj,
					platformUserNo);
			yeePayMessage.setRquestNo(requestNo);
			yeePayMessage.setPlatformUserNo(platformUserNo);
			insertDBLogger(yeePayMessage);
		} catch (Exception ex) {
			logger.error("执行签名操作失败!!", ex);
		}
		return response;
	}

	// 直接连接解冻
	private SuppleUnFreezeResponse doSignDirectUnFreeze(Object obj, String url,
			String service) {
		SuppleUnFreezeResponse response = null;
		try {
			StringWriter w = new StringWriter();
			JAXB.marshal(obj, w);
			String s = w.toString();
			s = s.replaceAll("[\\r\\n]", "");
			StringBuffer params = new StringBuffer();
			params.append("req=" + s);
			params.append("&service=" + service);
			params.append("&sign=" + "r7B");
			String returnValue = WebUtil.sendPost(directUrl, params.toString());
			if (!MobileUtil.isEmpty(returnValue)) {
				JaxbUtil resultBinder = new JaxbUtil(
						SuppleUnFreezeResponse.class, CollectionWrapper.class);
				response = resultBinder.fromXml(returnValue);
			}
			response.setMessage(params.toString());
			YeePayMessage yeePayMessage = writeLogger(response, obj);
			insertDBLogger(yeePayMessage);
		} catch (Exception ex) {
			logger.error("执行签名操作失败!!", ex);
		}
		return response;
	}

	// 直接连接账户
	private SuppleAccountResponse doSignDirectAccount(Object obj, String url,
			String service, String platformUserNo) {
		SuppleAccountResponse response = null;
		try {
			StringWriter w = new StringWriter();
			JAXB.marshal(obj, w);
			String s = w.toString();
			s = s.replaceAll("[\\r\\n]", "");
			StringBuffer params = new StringBuffer();
			params.append("req=" + s);
			params.append("&service=" + service);
			params.append("&sign=" + "r7B");
			String returnValue = WebUtil.sendPost(directUrl, params.toString());
			if (!MobileUtil.isEmpty(returnValue)) {
				JaxbUtil resultBinder = new JaxbUtil(
						SuppleAccountResponse.class, CollectionWrapper.class);
				response = resultBinder.fromXml(returnValue);
			}
			response.setMessage(params.toString());
			YeePayMessage yeePayMessage = writeLogger(response, obj,
					platformUserNo);
			yeePayMessage.setPlatformUserNo(platformUserNo);
			insertDBLogger(yeePayMessage);
		} catch (Exception ex) {
			logger.error("执行签名操作失败!!", ex);
		}
		return response;
	}

	// 直接连接单笔查询接口
	private SuppleSingleQueryResponse doSignSingleQuery(Object obj, String url,
			String service, String requestNo, YeePayModeEnum yeePayModeEnum) {
		SuppleSingleQueryResponse suppleSingleQueryResponse = new SuppleSingleQueryResponse();
		String platformUserNo = String.valueOf(UUIDUtil.getBigIntegerUUid());
		try {
			StringWriter w = new StringWriter();
			JAXB.marshal(obj, w);
			String s = w.toString();
			s = s.replaceAll("[\\r\\n]", "");
			StringBuffer params = new StringBuffer();
			params.append("req=" + s);
			params.append("&service=" + service);
			params.append("&sign=" + "r7B");
			String returnValue = WebUtil.sendPost(directUrl, params.toString());
			if (!MobileUtil.isEmpty(returnValue)) {
				if (yeePayModeEnum == YeePayModeEnum.RECHARGE_RECORD) { // 充值
					RechargeRecordResponse rechargeRecordResponse = null;
					JaxbUtil resultBinder = new JaxbUtil(
							RechargeRecordResponse.class,
							CollectionWrapper.class);
					rechargeRecordResponse = resultBinder.fromXml(returnValue);
					suppleSingleQueryResponse
							.setRechargeRecordResponse(rechargeRecordResponse);
					YeePayMessage yeePayMessage = writeLogger(
							suppleSingleQueryResponse, obj, platformUserNo,
							params.toString());
					yeePayMessage.setMessage(params.toString());
					yeePayMessage.setPlatformUserNo(platformUserNo);
					insertDBLogger(yeePayMessage);
				}
				if (yeePayModeEnum == YeePayModeEnum.WITHDRAW_RECORD) { // 提现
					WithdrawRecordResponse withdrawRecordResponse = null;
					JaxbUtil resultBinder = new JaxbUtil(
							WithdrawRecordResponse.class,
							CollectionWrapper.class);
					withdrawRecordResponse = resultBinder.fromXml(returnValue);
					suppleSingleQueryResponse
							.setWithdrawRecordResponse(withdrawRecordResponse);
					YeePayMessage yeePayMessage = writeLogger(
							suppleSingleQueryResponse, obj, platformUserNo,
							params.toString());
					yeePayMessage.setMessage(params.toString());
					yeePayMessage.setPlatformUserNo(platformUserNo);
					insertDBLogger(yeePayMessage);
				}
				if (yeePayModeEnum == YeePayModeEnum.CP_TRANSACTION) { // 划款
					CpTransactionResponse cpTransactionResponse = null;
					JaxbUtil resultBinder = new JaxbUtil(
							CpTransactionResponse.class,
							CollectionWrapper.class);
					cpTransactionResponse = resultBinder.fromXml(returnValue);
					suppleSingleQueryResponse
							.setCpTransactionResponse(cpTransactionResponse);
					YeePayMessage yeePayMessage = writeLogger(
							suppleSingleQueryResponse, obj, platformUserNo,
							params.toString());
					yeePayMessage.setMessage(params.toString());
					yeePayMessage.setPlatformUserNo(platformUserNo);
					insertDBLogger(yeePayMessage);
				}
				if (yeePayModeEnum == YeePayModeEnum.FREEZERE_RECORD) { // 冻结/解冻
					FreezereRecordResponse freezereRecordResponse = null;
					JaxbUtil resultBinder = new JaxbUtil(
							FreezereRecordResponse.class,
							CollectionWrapper.class);
					freezereRecordResponse = resultBinder.fromXml(returnValue);
					suppleSingleQueryResponse
							.setFreezereRecordResponse(freezereRecordResponse);
					YeePayMessage yeePayMessage = writeLogger(
							suppleSingleQueryResponse, obj, platformUserNo,
							params.toString());
					yeePayMessage.setMessage(params.toString());
					yeePayMessage.setPlatformUserNo(platformUserNo);
					insertDBLogger(yeePayMessage);
				}

			}

		} catch (Exception ex) {
			logger.error("执行签名操作失败!!", ex);
		}
		return suppleSingleQueryResponse;
	}

	// 直接连接-直接转账/自动转账授权
	private DirectTransactionResponse doDirectTransaction(Object obj,
			String url, String service, String requestNo, String platformUserNo) {
		DirectTransactionResponse response = null;
		try {
			StringWriter w = new StringWriter();
			JAXB.marshal(obj, w);
			String s = w.toString();
			s = s.replaceAll("[\\r\\n]", "");
			StringBuffer params = new StringBuffer();
			params.append("req=" + s);
			params.append("&service=" + service);
			params.append("&sign=" + "r7B");
			String returnValue = WebUtil.sendPost(directUrl, params.toString());
			if (!MobileUtil.isEmpty(returnValue)) {
				JaxbUtil resultBinder = new JaxbUtil(
						DirectTransactionResponse.class,
						CollectionWrapper.class);
				response = resultBinder.fromXml(returnValue);
			}
			response.setMessage(params.toString());
			if (service.equals("DIRECT_TRANSACTION")) {
				response.setServiceType("DIRECT_TRANSACTION");
			}
			if (service.equals("AUTO_TRANSACTION")) {
				response.setServiceType("AUTO_TRANSACTION");
			}
			if (service.equals("COMPLETE_TRANSACTION")) {
				response.setServiceType("COMPLETE_TRANSACTION");
			}
			if (service.equals("CANCEL_AUTHORIZE_AUTO_TRANSFER")) {
				response.setServiceType("CANCEL_AUTHORIZE_AUTO_TRANSFER");
			}
			if (service.equals("CANCEL_AUTHORIZE_AUTO_REPAYMENT")) {
				response.setServiceType("CANCEL_AUTHORIZE_AUTO_REPAYMENT");
			}
			YeePayMessage yeePayMessage = writeLogger(response, obj,
					platformUserNo);
			yeePayMessage.setRquestNo(requestNo);
			yeePayMessage.setPlatformUserNo(platformUserNo);
			insertDBLogger(yeePayMessage);
			Boolean isDb = true;
			if (service.equals("CANCEL_AUTHORIZE_AUTO_TRANSFER")
					|| service.equals("CANCEL_AUTHORIZE_AUTO_REPAYMENT")) {
				// 不需要要入库
				isDb = false;
			}
			if (isDb) {
				inserMongoDBKey(yeePayMessage, SignUtil.sign(s, pfx, "123qwe"));
			}

		} catch (Exception ex) {
			logger.error("执行签名操作失败!!", ex);
		}
		return response;
	}

	/**
	 * 写入网关日志
	 * 
	 * @param response
	 * @param obj
	 * @return
	 */
	private YeePayMessage writeLogger(YeePayBaseResponse response, Object obj) {
		String className = obj.getClass().getSimpleName();
		StringBuffer buffer = new StringBuffer();
		YeePayMessage yeePayMessage = new YeePayMessage();
		if (className.equals(YeePayClassTypeEnum.YeePayRegisterRequest
				.toString())) {
			buffer.append("执行注册用户操作请求;请求参数报文：" + response.getMessage());
			yeePayMessage.setOperateDescription("执行注册用户操作请求");
			yeePayMessage.setYeePaySubjoinEnum(YeePaySubjoinEnum.ACCOUNT_INFO);
			yeePayMessage.setYeePayServiceEnum(YeePayServiceEnum.REGISTER);
			yeePayMessage
					.setYeePayBussinesEnum(YeePayBussinesEnum.PERSONREGISTER);
		}
		if (className.equals(YeePayClassTypeEnum.YeePayRechargeRequest
				.toString())) {
			buffer.append("执行充值操作请求;请求参数报文：" + response.getMessage());
			yeePayMessage.setOperateDescription("执行充值操作请求");
			yeePayMessage.setYeePaySubjoinEnum(YeePaySubjoinEnum.QUERY);
			yeePayMessage.setYeePayServiceEnum(YeePayServiceEnum.RECHARGE);
		}
		if (className.equals(YeePayClassTypeEnum.YeePayWithdrawRequest
				.toString())) {
			buffer.append("执行提现操作请求;请求参数报文：" + response.getMessage());
			yeePayMessage.setOperateDescription("执行提现操作请求");
			yeePayMessage.setYeePaySubjoinEnum(YeePaySubjoinEnum.QUERY);
			yeePayMessage.setYeePayServiceEnum(YeePayServiceEnum.WITHDRAW);
		}
		if (className.equals(YeePayClassTypeEnum.YeePayBindRequest.toString())) {
			buffer.append("执行绑卡操作请求;请求参数报文：" + response.getMessage());
			yeePayMessage.setOperateDescription("执行绑卡操作请求");
			yeePayMessage.setYeePaySubjoinEnum(YeePaySubjoinEnum.ACCOUNT_INFO);
			yeePayMessage
					.setYeePayServiceEnum(YeePayServiceEnum.BIND_BANK_CARD);
		}

		if (className
				.equals(YeePayClassTypeEnum.YeePayUnBindRequest.toString())) {
			buffer.append("执行取消绑卡操作请求;请求参数报文：" + response.getMessage());
			yeePayMessage.setOperateDescription("执行取消绑卡操作请求");
			yeePayMessage.setYeePaySubjoinEnum(YeePaySubjoinEnum.ACCOUNT_INFO);
			yeePayMessage
					.setYeePayServiceEnum(YeePayServiceEnum.UNBIND_BANK_CARD);
		}
		if (className
				.equals(YeePayClassTypeEnum.YeePayEnterpriseRegisterRequest
						.toString())) {
			buffer.append("执行企业用户注册操作请求;请求参数报文：" + response.getMessage());
			yeePayMessage.setOperateDescription("执行企业用户注册操作请求");
			yeePayMessage.setYeePaySubjoinEnum(YeePaySubjoinEnum.ACCOUNT_INFO);
			yeePayMessage.setYeePayServiceEnum(YeePayServiceEnum.REGISTER);
			yeePayMessage
					.setYeePayBussinesEnum(YeePayBussinesEnum.ENTERREGISTER);
		}
		if (className.equals(YeePayClassTypeEnum.YeepayCpTransferRequest
				.toString())) {
			buffer.append("执行转账操作请求;请求参数报文：" + response.getMessage());
			yeePayMessage.setOperateDescription("执行转账操作请求");
			yeePayMessage.setYeePaySubjoinEnum(YeePaySubjoinEnum.QUERY);
			yeePayMessage.setYeePayServiceEnum(YeePayServiceEnum.TRANSACTION);
			yeePayMessage.setYeePayBussinesEnum(YeePayBussinesEnum.TRANSACTION);
		}
		if (className.equals(YeePayClassTypeEnum.YeePayAutoTransferRequest
				.toString())) {
			buffer.append("执行自动投标授权操作请求;请求参数报文：" + response.getMessage());
			yeePayMessage.setOperateDescription("执行自动投标授权操作请求");
			yeePayMessage.setYeePaySubjoinEnum(YeePaySubjoinEnum.ACCOUNT_INFO);
			yeePayMessage
					.setYeePayServiceEnum(YeePayServiceEnum.AUTHORIZE_AUTO_TRANSFER);
		}
		if (className.equals(YeePayClassTypeEnum.YeePayeAutoRepaymentRequest
				.toString())) {
			buffer.append("执行自动还款授权操作请求;请求参数报文：" + response.getMessage());
			yeePayMessage.setOperateDescription("执行自动还款授权操作请求");
			yeePayMessage.setYeePaySubjoinEnum(YeePaySubjoinEnum.QUERY);
			yeePayMessage
					.setYeePayServiceEnum(YeePayServiceEnum.AUTHORIZE_AUTO_REPAYMENT);
		}
		logger.error(buffer.toString());
		yeePayMessage.setMessage(buffer.toString());
		return yeePayMessage;
	}

	/**
	 * 写入网关日志
	 * 
	 * @param response
	 * @param obj
	 * @return
	 */
	private YeePayMessage writeLogger(YeePayBaseResponse response,
			CpExtendRequest cPrequest) {
		StringBuffer buffer = new StringBuffer();
		YeePayMessage yeePayMessage = new YeePayMessage();
		if (null != cPrequest.getTenderEntity() && null != cPrequest.getTenderEntity().getTenderOrderNo()) {
			buffer.append("执行投标操作请求;请求参数报文：" + response.getMessage());
			yeePayMessage.setOperateDescription("执行投标操作请求");
		}
		if (null != cPrequest.getRepaymentEntity() && null != cPrequest.getRepaymentEntity().getTenderOrderNo()) {
			buffer.append("执行还款操作请求;请求参数报文：" + response.getMessage());
			yeePayMessage.setOperateDescription("执行还款操作请求");
		}
		if (null != cPrequest.getCreditAssignment() && null != cPrequest.getCreditAssignment().getTenderOrderNo()) {
			buffer.append("执行债权转让操作请求;请求参数报文：" + response.getMessage());
			yeePayMessage.setOperateDescription("执行债权转让操作请求");
		}
		yeePayMessage.setYeePayServiceEnum(YeePayServiceEnum.TRANSACTION);
		yeePayMessage.setYeePaySubjoinEnum(YeePaySubjoinEnum.QUERY);
		yeePayMessage.setYeePayBussinesEnum(YeePayBussinesEnum.TRANSACTION);
		logger.error(buffer.toString());
		yeePayMessage.setMessage(buffer.toString());
		return yeePayMessage;
	}

	/**
	 * 写入直连资金冻结日志
	 * 
	 * @param response
	 * @param obj
	 * @return
	 */
	private YeePayMessage writeLogger(SuppleFreezeResponse response,
			Object obj, String platformUserNo) {
		StringBuffer buffer = new StringBuffer();
		buffer.append("执行资金冻结操作：" + response.getMessage());
		YeePayMessage yeePayMessage = new YeePayMessage();
		yeePayMessage.setPlatformUserNo(platformUserNo);
		yeePayMessage.setOperateDescription("执行资金冻结操作");
		yeePayMessage.setYeePaySubjoinEnum(YeePaySubjoinEnum.QUERY);
		yeePayMessage.setMessage(response.getMessage());
		logger.error(buffer.toString());
		return yeePayMessage;
	}

	/**
	 * 写入直连-直接转账/自动转账授权日志
	 * 
	 * @param response
	 * @param obj
	 * @return
	 */
	private YeePayMessage writeLogger(DirectTransactionResponse response,
			Object obj, String platformUserNo) {
		StringBuffer buffer = new StringBuffer();
		YeePayMessage yeePayMessage = new YeePayMessage();
		if (response.getServiceType().equals("DIRECT_TRANSACTION")) {
			buffer.append("执行直接转账授权操作：" + response.getMessage());
			yeePayMessage.setOperateDescription("执行直接转账操作");
			yeePayMessage
					.setYeePayBussinesEnum(YeePayBussinesEnum.DIRECT_TRANSACTION);
		}
		if (response.getServiceType().equals("AUTO_TRANSACTION")) {
			buffer.append("执行自动转账授权操作：" + response.getMessage());
			yeePayMessage.setOperateDescription("执行自动转账授权操作");
			yeePayMessage
					.setYeePayBussinesEnum(YeePayBussinesEnum.AUTO_TRANSACTION);
		}
		if (response.getServiceType().equals("COMPLETE_TRANSACTION")) {
			buffer.append("执行转账确认操作：" + response.getMessage());
			yeePayMessage.setOperateDescription("执行转账确认操作");
			yeePayMessage
					.setYeePayBussinesEnum(YeePayBussinesEnum.COMPLETE_TRANSACTION);
		}
		if (response.getServiceType().equals("CANCEL_AUTHORIZE_AUTO_TRANSFER")) {
			buffer.append("执行取消自动投标授权操作：" + response.getMessage());
			yeePayMessage.setOperateDescription("执行取消自动投标授权操作");
		}
		if (response.getServiceType().equals("CANCEL_AUTHORIZE_AUTO_REPAYMENT")) {
			buffer.append("执行取消自动还款授权操作：" + response.getMessage());
			yeePayMessage.setOperateDescription("执行取消自动还款授权操作");
		}
		yeePayMessage.setPlatformUserNo(platformUserNo);
		yeePayMessage.setYeePaySubjoinEnum(YeePaySubjoinEnum.QUERY);
		yeePayMessage.setMessage(response.getMessage());
		logger.error(buffer.toString());
		return yeePayMessage;
	}

	/**
	 * 写入直连资金冻结日志
	 * 
	 * @param response
	 * @param obj
	 * @return
	 */
	private YeePayMessage writeLogger(SuppleSingleQueryResponse response,
			Object obj, String platformUserNo, String message) {
		StringBuffer buffer = new StringBuffer();
		buffer.append("执行单笔查询操作：" + message);
		YeePayMessage yeePayMessage = new YeePayMessage();
		yeePayMessage.setPlatformUserNo(platformUserNo);
		yeePayMessage.setOperateDescription("执行单笔查询操作");
		yeePayMessage.setYeePaySubjoinEnum(YeePaySubjoinEnum.QUERY);
		yeePayMessage.setMessage(message);
		logger.error(buffer.toString());
		return yeePayMessage;
	}

	/**
	 * 写入直连资金解冻日志
	 * 
	 * @param response
	 * @param obj
	 * @return
	 */
	private YeePayMessage writeLogger(SuppleUnFreezeResponse response,
			Object obj) {
		StringBuffer buffer = new StringBuffer();
		buffer.append("执行资金冻结操作：" + response.getMessage());
		YeePayMessage yeePayMessage = new YeePayMessage();
		yeePayMessage.setOperateDescription("执行资金冻结操作");
		yeePayMessage.setYeePaySubjoinEnum(YeePaySubjoinEnum.QUERY);
		yeePayMessage.setMessage(response.getMessage());
		// 解冻没有请求Id，赋值一个
		String requestNo = "nwUnf_"
				+ String.valueOf(UUIDUtil.getBigIntegerUUid());
		yeePayMessage.setRquestNo(requestNo);
		logger.error(buffer.toString());
		return yeePayMessage;
	}

	/**
	 * 写入直连账户查询日志
	 * 
	 * @param response
	 * @param obj
	 * @return
	 */
	private YeePayMessage writeLogger(SuppleAccountResponse response,
			Object obj, String platformUserNo) {
		String requestNo = "nwAcc_"
				+ String.valueOf(UUIDUtil.getBigIntegerUUid());
		StringBuffer buffer = new StringBuffer();
		buffer.append("执行直连账户查询：" + response.getMessage());
		YeePayMessage yeePayMessage = new YeePayMessage();
		yeePayMessage.setPlatformUserNo(platformUserNo);
		yeePayMessage.setOperateDescription("执行直连账户查询");
		yeePayMessage.setMessage(response.getMessage());
		yeePayMessage.setRquestNo(requestNo);
		logger.error(buffer.toString());
		return yeePayMessage;
	}

	/**
	 * 日志入库
	 * 
	 * @param yeePayMessage
	 */
	private void insertDBLogger(YeePayMessage yeePayMessage) {
		if (null == yeePayMessage.getMessage()
				|| null == yeePayMessage.getOperateDescription()) {
			logger.error("易宝日志记录入参不能为空");
			return;
		}
		if (null == yeePayMessage.getRquestNo()
				|| null == yeePayMessage.getPlatformUserNo()) {
			logger.error("易宝日志记录入参不能为空");
			return;
		}
		YeePayLogInfo yeePayLogInfo = new YeePayLogInfo();
		yeePayLogInfo.setOperateDescription(yeePayMessage
				.getOperateDescription());
		yeePayLogInfo.setRequestMessage(yeePayMessage.getMessage());
		yeePayLogInfo.setRquestNo(yeePayMessage.getRquestNo());
		yeePayLogInfo.setPlatformUserNo(yeePayMessage.getPlatformUserNo());
		yeePayLogInfo.setCreated(new Date());
		yeePayLogInfo.setDispose(0);//默认未处理
		yeePayLogService.saveLog(yeePayLogInfo);
	}

	/**
	 * 进入mongoDb队列 [补单机制准备]
	 */
	public void inserMongoDBKey(YeePayMessage yeePayMessage, String sign) {
		if (null == yeePayMessage.getRquestNo()
				|| null == yeePayMessage.getPlatformUserNo()) {
			logger.error("易宝mongoDb入参不能为空");
			return;
		}
		YeePayMongoInfo yeePayMongoInfo = new YeePayMongoInfo();
		yeePayMongoInfo.setRequestNo(yeePayMessage.getRquestNo());
		yeePayMongoInfo.setRequestMessage(yeePayMessage.getMessage());
		yeePayMongoInfo.setSign(sign);
		yeePayMongoInfo.setYeePaySubjoinEnum(yeePayMessage
				.getYeePaySubjoinEnum());
		yeePayMongoInfo.setPlatformUserNo(yeePayMessage.getPlatformUserNo());
		yeePayMongoInfo.setYeePayServiceEnum(yeePayMessage
				.getYeePayServiceEnum());
		yeePayMongoInfo.setYeePayBussinesEnum(yeePayMessage
				.getYeePayBussinesEnum());
		yeePayMongoService.save(yeePayMongoInfo);
	}
}
